package com.bigknow.appstore.proxy.timetask.impl;

import com.bigknow.appstore.proxy.timetask.ITimeWorker;
import com.bigknow.appstore.proxy.util.HandlerVariables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 由于开启lastRequest功能后，如果不定制策略，定时清除lastRquest会造成后续的错误链接访问
 * 都会跳转到最后一个正确访问的服务路径，造成混乱，所以必须定时清除
 * Created by chaos on 2016/9/26.
 */
public class LastRequestVoRemoveWorker implements ITimeWorker, Runnable {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Map<String, Date> timeMap = new ConcurrentHashMap<>();

    /**
     * 默认30秒执行一次
     */
    private int checkTime = 30000;

    private int lastRequestSurvivalTime;

    private AtomicBoolean isRun = new AtomicBoolean(false);

    public LastRequestVoRemoveWorker(int lastRequestSurvivalTime) {
        this.lastRequestSurvivalTime = lastRequestSurvivalTime;
    }

    @Override
    public void start() {
        isRun.set(true);
        new Thread(this).start();
    }

    @Override
    public void stop() {
        isRun.set(false);
    }

    @Override
    public void setCheckTime(int checkTime) {
        this.checkTime = checkTime;
    }

    @Override
    public void run() {
        while (isRun.get()) {
            for (String id : timeMap.keySet()) {
                long startTime = timeMap.get(id).getTime();
                if(lastRequestSurvivalTime==0) continue;
                if (new Date().getTime() - startTime > lastRequestSurvivalTime) {
                    logger.info("remove timeout last request client id is: " + id);
                    HandlerVariables.lastRequestVos.remove(id);
                    timeMap.remove(id);
                }
            }
            try {
                Thread.sleep(checkTime);
            } catch (InterruptedException e) {
            }
        }
    }

    /**
     * 设置加入lastRequest的时间
     *
     * @param id
     */
    public void addLastRequestTime(String id) {
        timeMap.put(id, new Date());
    }
}
